const express = require('express');
const path = require('path');
const fs = require('fs').promises;

const app = express();
const PORT = 22150;

// 启用所有CORS请求
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// 添加解析JSON请求体的中间件
app.use(express.json({ limit: '10mb' }));

// 引入路由
const router = require('./router');
app.use('/', router);

// 提供静态文件服务
app.use(express.static(path.join(__dirname, '../views')));

// 设置EJS为模板引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '../codeTemplate'));

// 引入并启动定时清理任务
const { startCleanupSchedule ,cleanupTempDirectory} = require('./cleanupTempFiles');
startCleanupSchedule();
cleanupTempDirectory()

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
  console.log(`Open your browser to http://localhost:${PORT}/index.html`);
  
  // 尝试打开浏览器，如果失败则只打印消息
  try {
    // const open = require('open');
    // open(`http://localhost:${PORT}/index.html`).catch(err => {
    //   console.log('Could not automatically open browser:', err.message);
    // });
  } catch (err) {
    console.log("🚀 ~ err:", err)
    console.log('Open package not available, please manually open the URL');
  }
});